import React from 'react';
import { connect } from 'umi';
import { Row, Card, Radio, DatePicker, Col, TreeSelect } from 'antd';
import moment from 'moment';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Statistic, DepartmentTree } from '../components';
import EmployeeList from './EmployeeList';
import TaskBar from './TaskBar';
import QualityBar from './QualityBar';
import TaskPie from './TaskPie';
import { useDepartmentOverview, useCompanyTree, useDepartmentTree } from '../hooks';
import { formatDate, limitDate } from '../utils';

import styles from './overview.less';

const Overview = ({ location }) => {
    /* 组件内部维护查询参数 */
    const { query } = location;
    const [params, setParams] = React.useState({
        companyId: query.companyId || 101,
        departmentId: query.departmentId || 104,
        reportType: query.reportType || '1',
        startDate: query.startDate || formatDate('1', moment()).startDate,
        endDate: query.endDate || formatDate('1', moment()).endDate
    });

    const [date, setDate] = React.useState(moment(query.startDate) || moment());

    /* 组件状态 */
    const [selectedDepartmentId, setSelectedDepartmentId] = React.useState('');
    const [taskType, setTaskType] = React.useState('1'); // 1：计划工作量分布 2：实际工作量分布
    const handleTaskType = e => {
        setTaskType(e.target.value);
    };

    /* Domain 数据 */
    const [companyLoading, companyData] = useCompanyTree();
    const [departmentLoading, departmentData = []] = useDepartmentTree(params.companyId);
    const [overviewLoading, overviewData] = useDepartmentOverview(params);

    /* 一级部门 */
    const departmentTreeData = departmentData.map(item => ({ ...item, children: [] }));

    /* 注意：departmentId 不能为空，如果没值默认取列表第一个 */
    // React.useEffect(() => {
    //     if (departmentData && !departmentLoading) {
    //         const hasDepartmentId = departmentData.some(item => item.id === Number(query.departmentId));
    //         if (hasDepartmentId) {
    //             return;
    //         }
    //         setParams({ ...params, departmentId: departmentData[0].id });
    //     }
    // }, [departmentData, departmentLoading]);

    /* 当前选中的部门信息 */
    const selectedDepartment = React.useMemo(
        () => departmentData.find(item => item.id === Number(params.departmentId)) || {},
        [departmentData, params.departmentId, query]
    );

    /* 二级部门 */
    const treeData = departmentData.filter(
        item => item.id === Number(params.departmentId) || item.id === selectedDepartment.parentId
    );

    const {
        totalPeopleNum = 0, // 部门员工
        evalPeopleNum = 0, // 考核员工
        employeeEvalRateStr = 0, // 考核率
        totalTaskNum = 0, // 总任务
        doneTaskNum = 0, // 正常完成
        normalDoneTaskNum = 0, // 已完成
        overdueTaskNum = 0, // 逾期
        standardPerCapitaWorkloadNum = 0, // 人均额定
        planPerCapitaStandardWorkloadNum = 0, // 计划人均
        actualPerCapitaWorkloadNum = 0, // 实际人均
        evalScore = 0, // 平均版本质量
        rankName = '--', // 评估结果
        dailyBugNum = 0, // 平均bug
        overdueDoneTaskNum = 0, // 逾期达成
        overdueNonexecutionTaskNum = 0, // 逾期未达成,
        planWorkloadNormalPeopleNum = 0, // 工作量正常人数
        planWorkloadLackPeopleNum = 0, // 工作量不足人数
        planWorkloadExcessPeopleNum = 0, // 工作量超额人数
        actualWorkloadNormalPeopleNum = 0, // 工作量正常人数
        actualWorkloadLackPeopleNum = 0, // 工作量不足人数
        actualWorkloadExcessPeopleNum = 0, // 工作量超额人数
        departmentQualityRankVOList = [] // 质量分布
    } = overviewData;

    const getTaskLink = _params => ({
        pathname: '/stat/workStat/workOverview/work/task',
        query: { ...params, ..._params }
    });

    /* 任务完成情况 */
    const statistic1 = [
        {
            value: totalTaskNum,
            label: '总任务',
            link: getTaskLink()
        },
        {
            value: doneTaskNum,
            label: '已完成',
            link: getTaskLink({ taskStatus: '完成' })
        },
        {
            value: overdueTaskNum,
            label: '逾期',
            link: getTaskLink({ taskCompleteStatus: '逾期' })
        }
    ];

    /* 人均工作量 */
    const statistic2 = [
        { value: standardPerCapitaWorkloadNum, label: '人均额定', unit: '小时' },
        { value: planPerCapitaStandardWorkloadNum, label: '计划人均', unit: '小时' },
        { value: actualPerCapitaWorkloadNum, label: '实际人均', unit: '小时' }
    ];
    /* 人均工作量 */
    const statistic3 = [
        { value: evalScore, label: '平均版本质量', unit: '分' },
        { value: rankName, label: '评估结果' },
        { value: dailyBugNum, label: '日均 Bug' }
    ];

    /* 任务达成分布 */
    const chartData1 = [
        { name: '正常达成', num: normalDoneTaskNum },
        { name: '逾期达成', num: overdueDoneTaskNum },
        { name: '逾期未达成', num: overdueNonexecutionTaskNum }
    ];

    /* 实际工作量分布 */
    const actualData = [
        { name: '正常', num: actualWorkloadNormalPeopleNum },
        { name: '不足', num: actualWorkloadLackPeopleNum },
        { name: '超额', num: actualWorkloadExcessPeopleNum }
    ];

    /* 计划工作量分布 */
    const planData = [
        { name: '正常', num: planWorkloadNormalPeopleNum },
        { name: '不足', num: planWorkloadLackPeopleNum },
        { name: '超额', num: planWorkloadExcessPeopleNum }
    ];

    /* 任务质量 */
    const chartData3 = departmentQualityRankVOList;

    const handleDateTypeChange = React.useCallback(
        e => {
            const { value } = e.target;
            setParams({ ...params, reportType: value, ...formatDate(value, date) });
        },
        [params]
    );

    const handleCompanyChange = React.useCallback(
        companyId => {
            setParams({ ...params, companyId, departmentId: '' });
        },
        [params]
    );

    const handleDepartmentChange = React.useCallback(
        departmentId => {
            setParams({ ...params, departmentId });
        },
        [params]
    );

    const handleDate = React.useCallback(
        value => {
            setDate(value);
            setParams({ ...params, ...formatDate(params.reportType, value) });
        },
        [params]
    );

    const extra = (
        <div>
            <span className={styles.extraTitle}>部门员工/考核员工：</span>
            <span className={styles.extraText}>
                {totalPeopleNum}/{evalPeopleNum}
            </span>
            <span className={styles.extraTitle} style={{ marginLeft: 24 }}>
                考核率：
            </span>
            <span className={styles.extraText}>{`${employeeEvalRateStr}`}</span>
        </div>
    );

    const DateComponent = String(params.reportType) === '1' ? DatePicker.WeekPicker : DatePicker.MonthPicker;
    const employeeParam = React.useMemo(
        () => ({ ...params, departmentId: selectedDepartmentId || params.departmentId }),
        [params, selectedDepartmentId]
    );

    // @TODO 公司部门树下拉组件待重构
    return (
        <PageHeaderWrapper>
            <Card>
                <Row type="flex">
                    <TreeSelect
                        showSearch
                        treeDefaultExpandAll
                        loading={companyLoading}
                        treeData={companyData}
                        value={params.companyId}
                        onChange={handleCompanyChange}
                        treeNodeFilterProp="title"
                        style={{ width: 160, marginRight: 8 }}
                    />
                    <TreeSelect
                        showSearch
                        loading={departmentLoading}
                        treeData={departmentTreeData}
                        value={params.departmentId}
                        onChange={handleDepartmentChange}
                        treeNodeFilterProp="title"
                        style={{ width: 160, marginRight: 24 }}
                    />
                    <Radio.Group value={params.reportType} onChange={handleDateTypeChange} style={{ marginRight: 16 }}>
                        <Radio.Button value="1">周</Radio.Button>
                        <Radio.Button value="2">月</Radio.Button>
                    </Radio.Group>
                    <DateComponent
                        disabledDate={current => limitDate(current, params.reportType)}
                        value={date}
                        onChange={handleDate}
                    />
                </Row>
            </Card>

            <Card
                title={selectedDepartment.title && `${selectedDepartment.title} - 工作概况`}
                loading={overviewLoading}
                extra={selectedDepartment.title && extra}
                style={{ marginTop: 12 }}
            >
                <Row type="flex" gutter={48}>
                    <Col span={8} style={{ borderRight: '1px solid #eee' }}>
                        <Statistic title="任务完成情况" data={statistic1} />
                        <div style={{ margin: '24px 0 16px 0', fontWeight: 600 }}>任务达成分布</div>
                        <TaskBar data={chartData1} query={params} />
                    </Col>

                    <Col span={8} style={{ borderRight: '1px solid #eee' }}>
                        <Statistic title="人均工作量" data={statistic2} />
                        <div style={{ margin: '24px 0 16px 0' }}>
                            <Radio.Group value={taskType} onChange={handleTaskType}>
                                <Radio.Button value="1">计划工作量分布</Radio.Button>
                                <Radio.Button value="2">实际工作量分布</Radio.Button>
                            </Radio.Group>
                        </div>
                        <TaskPie data={taskType === '1' ? planData : actualData} query={params} />
                    </Col>

                    <Col span={8}>
                        <Statistic title="任务质量" data={statistic3} />
                        <QualityBar data={chartData3} style={{ height: 365 }} query={params} />
                    </Col>
                </Row>
            </Card>

            <Card
                title={selectedDepartment.title && `${selectedDepartment.title} - 考核员工清单`}
                loading={overviewLoading}
                style={{ marginTop: 12 }}
            >
                <Row gutter={24}>
                    <Col span={4}>
                        {treeData.length !== 0 && (
                            <DepartmentTree
                                treeData={treeData}
                                onSelect={val => {
                                    setSelectedDepartmentId(val[0]);
                                }}
                            />
                        )}
                    </Col>
                    <Col span={20}>
                        <EmployeeList param={employeeParam} />
                    </Col>
                </Row>
            </Card>
        </PageHeaderWrapper>
    );
};

const mapStateToProps = ({ user }) => ({ user });

export default connect(mapStateToProps)(Overview);
